﻿using AutoMapper;
using Enter.Dashboard.Api.Dtoes.Requests;
using Enter.Dashboard.Api.Entities;
using Enter.Dashboard.Api.Filters;
using Enter.Enums;
using Enter.Utils;
using Enter.Utils.CryptoExt;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Caching.Distributed;
using Microsoft.Extensions.Logging;

namespace Enter.Dashboard.Api.Controllers
{
    [ApiController]
    [Route("[controller]/[action]")]
    [Produces("application/json")]
    [AuthorizationAttribute(NeedLogin = false)]
    public class LoginController : BaseController
    {
        //private readonly IMapper _mapper;

        public LoginController(ILogger<LoginController> logger, IDistributedCache cache, IFreeSql fsql, IMapper mapper) : base(logger, cache, fsql, mapper)
        {
            //_mapper = mapper;
        }

        [HttpPost]
        public ResponseData<Employ> Do([FromBody]LoginRequest request)
        {
            var md5_password = CryptoExtend.Md5(request.Password);
            var user = _fsql.Select<Employ>().Include(t => t.Role)
                        .Where(t => t.UserName == request.UserName && t.Password == md5_password && t.IsDeleted == false).First();
            if (user != null && user.State == (int)EnumEmployState.正常)
            {
                var tokenStr = UpdateSession(userId: user.Id, user: user);
                return new ResponseData<Employ>()
                {
                    Success = true,
                    Data = user,
                    Token = tokenStr,
                    Message = "登录成功."
                };
            }
            return ResponseData<Employ>.ERROR("用户名或密码错误.");
        }

        [HttpPost]
        public ResponseData<string> Logout()
        {
            var token = Token();
            if (token != null)
            {
                _cache.Remove(token.Id);
            }
            return new ResponseData<string> ()
            {
                Success = true,
                Code = ResponseCode.NotLogin
            };
        }
    }
}
